/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.employee.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.employee.entity.Employee;
import com.thinkgem.jeesite.modules.employee.service.EmployeeService;
import com.thinkgem.jeesite.modules.schedul.entity.Schclass;

/**
 * 人事信息管理Controller
 * @author hui.li
 * @version 2017-07-15
 */
@Controller
@RequestMapping(value = "${adminPath}/employee/employee")
public class EmployeeController extends BaseController {

	@Autowired
	private EmployeeService employeeService;
	
	@ModelAttribute
	public Employee get(@RequestParam(required=false) String id) {
		Employee entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = employeeService.get(id);
		}
		if (entity == null){
			entity = new Employee();
		}
		return entity;
	}
	
	@RequiresPermissions("employee:employee:view")
	@RequestMapping(value = {"list", ""})
	public String list(Employee employee, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Employee> page = employeeService.findPage(new Page<Employee>(request, response), employee); 
		model.addAttribute("page", page);
		return "modules/employee/employeeList";
	}

	@RequiresPermissions("employee:employee:view")
	@RequestMapping(value = "form")
	public String form(Employee employee, Model model) {
		model.addAttribute("employee", employee);
		return "modules/employee/employeeForm";
	}

	@RequiresPermissions("employee:employee:edit")
	@RequestMapping(value = "save")
	public String save(Employee employee, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, employee)){
			return form(employee, model);
		}
		employeeService.save(employee);
		addMessage(redirectAttributes, "保存人事信息管理成功");
		return "redirect:"+Global.getAdminPath()+"/employee/employee/list?repage";
	}
	
	@RequiresPermissions("employee:employee:edit")
	@RequestMapping(value = "delete")
	public String delete(Employee employee, RedirectAttributes redirectAttributes) {
		employeeService.delete(employee);
		addMessage(redirectAttributes, "删除人事信息管理成功");
		return "redirect:"+Global.getAdminPath()+"/employee/employee/list?repage";
	}
	
	/**
	 * 导出员工数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("employee:employee:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Employee employee, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "员工信息数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Employee> page = employeeService.findPage(new Page<Employee>(request, response, -1), employee);
    		new ExportExcel("员工信息数据", Employee.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出员工失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/employee/employee/list?repage";
    }
	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("employee:employee:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/employee/employee/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 0, 0);
			List<Employee> list = ei.getDataList(Employee.class);
			for (Employee employee : list){
				try{
					if ("true".equals(checkEmployeeNumber(employee.getNumber()))){
						// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
						//employee.setCompany(new Office(request.getParameter("company.id")));
						//employee.setOffice(new Office(request.getParameter("office.id")));
						
						employeeService.save(employee);
						successNum++;
					}else{
						failureMsg.append("<br/>工号 "+employee.getNumber()+" 已存在; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>工号 "+employee.getNumber()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>工号 "+employee.getNumber()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条员工，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条员工"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入员工失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/employee/employee/list?repage";
    }
	
	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("employee:employee:edit")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "员工数据导入模板.xlsx";
    		List<Employee> list = Lists.newArrayList();
    		new ExportExcel("", Employee.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/employee/employee/list?repage";
    }
	
	/**
	 * 验证登录名是否有效
	 * @param number 工号
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("employee:employee:edit")
	@RequestMapping(value = "checkEmployeeNumber")
	public String checkEmployeeNumber(String number) {
		if (number !=null && employeeService.getcheckEmployeeNumber(number) == null) {
			return "true";
		}
		return "false";
	}
	
	@RequiresPermissions("employee:employee:schedulList")
    @RequestMapping(value = {"schedulList", ""})
    public String schedulList(Employee employee, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Employee> page = employeeService.findPage(new Page<Employee>(request, response), employee); 
        model.addAttribute("page", page);
        return "modules/schedul/schedulEmployeeList";
    }

	/**
	 *  异步调用，查询员工列表
	 * @param Employee
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = {"getEmployeeList"})
	public Map<String,Object> getEmployeeList(String schclass,Employee employee, HttpServletRequest request,HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try
		{
			Page<Employee> page = employeeService.findPageEmployee(schclass,new Page<Employee>(request, response), employee); 
					
			if(null == page){
				resultMap.put("success", false);
			}else{
				resultMap.put("success", true);
				if(null != page.getList() && page.getList().size()>0)
				{
					resultMap.put("data", page);
				}			
			}
		} catch (Exception e)
		{
			resultMap.put("success", false);
			e.printStackTrace();
		}
		return resultMap;
	}
	
	/**
     * 获取员工名称JSON数据。
     * @param 
     * @param response
     * @return
     */
	@RequiresPermissions("employee:employee:schedulList")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Employee> list = employeeService.findList(new Employee());
        for (int i=0; i<list.size(); i++){
            Employee e = list.get(i);
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("number", e.getNumber());
                map.put("name",e.getName());
                
                mapList.add(map);
        }
        return mapList;
    }

	
	/**
	 * 
	 * 查询异常打卡列表
	 * @param employee
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("employee:employee:view")
    @RequestMapping(value = {"queryExceptionEmployee", ""})
    public String queryExceptionEmployee(Employee employee, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Employee> page = employeeService.queryExceptionEmployee(new Page<Employee>(request, response), employee); 
        model.addAttribute("page", page);
        return "modules/employee/exceptionEmployee";
    }
	
	
	
}